package com.distribute.framework.core.web.helper;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;

import com.distribute.framework.core.util.zip.ZipEntry;
import com.distribute.framework.core.util.zip.ZipOutputStream;

public class FileHelper
{

	/**
	 * 写文件
	 * @param string
	 * @param fileName
	 */
	public static void writeFile(String fileName,String content,String encode)
	{
		if(encode==null)
			encode="UTF-8";
		try{
			fileName=fileName.replaceAll("\\\\", "/");
			fileName=fileName.replaceAll("//", "/");
			
			String filePath=fileName.substring(0,fileName.lastIndexOf("/"));
			
			if(!new File(filePath).exists())
				new File(filePath).mkdirs();
			
			FileOutputStream fos = new FileOutputStream(fileName);
			Writer out = new OutputStreamWriter(fos,encode);
			out.write(content);
			out.close();
			fos.flush();
			fos.close();
		} catch (IOException ex) {			
			System.out.println("写文件["+fileName+"]到["+fileName+"]时出错:"+ex.getMessage());
			ex.printStackTrace();
		}
	}
	
	
	/**
	 * 拷贝文件
	 * @param srcFilename
	 * @param destFilename
	 * @return 目的文件路径
	 * @throws Exception
	 */
	public static String copyFile(String srcFilename,String destFilename) throws Exception
	{		
   		java.io.File srcFile=new java.io.File(srcFilename);
   		java.io.File destFile=new java.io.File(destFilename);
   		String apath = destFile.getAbsolutePath().replace("\\", "/");
   		new File(apath.substring(0,apath.lastIndexOf("/"))).mkdirs();
   		FileInputStream in=new FileInputStream(srcFile);
   		FileOutputStream out=new FileOutputStream(destFile);
   		byte[] bytes=new byte[1024];
   		int c;
   		while((c=in.read(bytes))!=-1)
   			out.write(bytes,0,c);
   		in.close();
   		out.close();
   		return destFilename;
	}
	
	/**
	 * 读文件
	 * @param srcFilename
	 * @param encode
	 * @return 文件内容
	 * @throws Exception
	 */
	public static String readFile(String srcFilename) throws Exception
	{	
		FileInputStream fis = new FileInputStream(srcFilename);
		byte []bytes=new byte[fis.available()];
		byte blocks[] = new byte[1024];
		int nowSize = 0;
		int realRead = 0;
		while ((realRead = fis.read(blocks, 0, 1024)) != -1) {
			if(nowSize==0 && realRead>3 && blocks[0] == -17 && blocks[1] == -69 && blocks[2] == -65){
				bytes=new byte[bytes.length-3];
				System.arraycopy(blocks, 3, blocks, 0, realRead-=3);
			}
			System.arraycopy(blocks, 0, bytes, nowSize, realRead);
			blocks = new byte[1024];
			nowSize += realRead;
		}
		fis.close();
   		return new String(bytes,getCharset(new FileInputStream(srcFilename)));
	}
	
	/**
	 * 读文件
	 * @param srcFilename
	 * @param encode
	 * @return 文件内容
	 * @throws Exception
	 */
	public static String readFile(InputStream input,String encode) throws Exception
	{	
		BufferedReader reader=new BufferedReader(new InputStreamReader(input,encode));
		String fileString="";
		String strLine=null;
		while((strLine=reader.readLine())!=null)
			fileString+=strLine+"\n";
   		return fileString;
	}

	/**
	 * 写流到文件
	 * @param input
	 * @param destFilename
	 * @return
	 * @throws Exception
	 */
	public static String writeStreamToFile(InputStream input, String fileName)throws Exception
	{
		fileName=fileName.replaceAll("\\\\", "/");
		fileName=fileName.replaceAll("//", "/");
		
		String filePath=fileName.substring(0,fileName.lastIndexOf("/"));
		
		if(!new File(filePath).exists())
			new File(filePath).mkdirs();
		
   		java.io.File destFile=new java.io.File(fileName);
   		FileOutputStream out=new FileOutputStream(destFile);
   		byte[] bytes=new byte[1024];
   		int c;
   		while((c=input.read(bytes))!=-1)
   			out.write(bytes,0,c);
   		out.close();
   		return fileName;
	}
	
	public static String getCharset(String filename) {
		try {
			return getCharset(new FileInputStream(new File(filename)));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
		
	}
	
	/**
	 * 获取文件编码
	 * @param file
	 * @return
	 * ANSI：无格式定义；
	 * Unicode： 前两个字节为FFFE；
	 * Unicode big endian：前两字节为FEFF；　 
	 * UTF-8：前两字节为EFBB；
	 */
	public static String getCharset( InputStream is ) {   
        String charset = "GBK";   
        byte[] first3Bytes = new byte[3];   
        try {
            boolean checked=false;   
            BufferedInputStream bis = new BufferedInputStream(is);   
            bis.mark( 0 );   
            int read = bis.read( first3Bytes, 0, 3 );   
            if ( read == -1 ) return charset;   
            if ( first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE ) {   
                charset = "UTF-16LE";   
                checked = true;   
            }   
            else if ( first3Bytes[0] == (byte) 0xFE && first3Bytes[1] == (byte) 0xFF ) {   
                charset = "UTF-16BE";   
                checked = true;   
            }   
            else if ( first3Bytes[0] == (byte) 0xEF && first3Bytes[1] == (byte) 0xBB && first3Bytes[2] == (byte) 0xBF ) {   
                charset = "UTF-8";   
                checked = true;   
            }   
            bis.reset();   
            if ( !checked ) {   
                int loc = 0;
                while ( (read = bis.read()) != -1 ) {   
                    loc++;   
                    if ( read >= 0xF0 ) break;   
                    if ( 0x80 <= read && read <= 0xBF ) // 单独出现BF以下的，也算是GBK   
                    break;   
                    if ( 0xC0 <= read && read <= 0xDF ) {   
                        read = bis.read();   
                        if ( 0x80 <= read && read <= 0xBF ) // 双字节 (0xC0 - 0xDF) (0x80   
                                                                        // - 0xBF),也可能在GB编码内   
                        continue;   
                        else break;   
                    }   
                    else if ( 0xE0 <= read && read <= 0xEF ) {// 也有可能出错，但是几率较小   
                        read = bis.read();   
                        if ( 0x80 <= read && read <= 0xBF ) {   
                            read = bis.read();   
                            if ( 0x80 <= read && read <= 0xBF ) {   
                                charset = "UTF-8";   
                                break;   
                            }   
                            else break;   
                        }   
                        else break;   
                    }   
                }
                bis.close();
            }
            return charset; 
        } catch ( Exception e ) {   
            e.printStackTrace(); 
            return null;
        }
    }
	
	
	/**
	 * 压缩文件
	 * @param item
	 * @throws Exception 
	 */
	public static void zip(File zipFile, File...files) throws Exception {
		FileOutputStream fos = new FileOutputStream(zipFile);
		BufferedOutputStream bos = new BufferedOutputStream(fos);
		ZipOutputStream zos = new ZipOutputStream(fos,"GBK");//压缩包

		byte[] buf = new byte[1024];
		int len;

		for(File file:files){
			//把上传的文件压缩到压缩文件		
			ZipEntry ze = new ZipEntry(file.getName());//这是压缩包名里的文件名
			zos.putNextEntry(ze);//写入新的 ZIP 文件条目并将流定位到条目数据的开始处
		    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
			while ((len = bis.read(buf)) != -1) {
				zos.write(buf, 0, len);
				zos.flush();
			}
			bis.close();
		}

		zos.flush();
		zos.close();
	}
		
}